import { defineConfig, loadEnv } from "vite";
import UnoCSS from "unocss/vite";
import vue from "@vitejs/plugin-vue";
import path, { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { VantResolver } from "@vant/auto-import-resolver";
import vueJsx from "@vitejs/plugin-vue-jsx";
import postCssPxToRem from "postcss-pxtorem";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import { ViteImageOptimizer } from "vite-plugin-image-optimizer";
import { createHtmlPlugin } from "vite-plugin-html";
import { appWidth, divide, unitPrecision } from "./src/config/index.ts";
import { enableCDN } from "./src/config/cdn.ts";
// @ts-ignore
import { svgBuilder } from "./src/plugins/svgBuilder.js";

export default defineConfig(({ mode }) => {
  const envDir = "./env";
  const config = loadEnv(mode, resolve(process.cwd(), envDir));
  return {
    base: "/",
    envDir: envDir,
    envPrefix: ["VITE_"],
    plugins: [
      UnoCSS(),
      svgBuilder("./src/assets/svg/"),
      enableCDN(config.VITE_ENV != "production"),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: {
            title: "Home"
          }
        }
      }),
      vue(),
      vueJsx(),
      AutoImport({
        imports: ["vue", "vue-router", "vue-i18n"],
        resolvers: [VantResolver()],
        dirs: ["./src/utils/*", "./src/assets/js/*"],
        dts: "src/types/auto-import.d.ts",
        include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/]
      }),
      Components({
        resolvers: [VantResolver()],
        dirs: ["src/components"],
        dts: "src/types/components.d.ts",
        extensions: ["vue"],
        globalNamespaces: []
      }),
      VueSetupExtend(),
      ViteImageOptimizer({
        png: {
          quality: 100
        },
        jpg: {
          quality: 100
        },
        jpeg: {
          quality: 100
        },
        webp: {
          quality: 100
        }
      })
    ],
    build: {
      outDir: "dist",
      assetsDir: "assets",
      sourcemap: false,
      minify: "terser",
      chunkSizeWarningLimit: 1024 * 10,
      terserOptions: {
        output: {
          comments: false,
          beautify: false
        },
        compress: {
          drop_console: false,
          drop_debugger: true
        }
      },
      rollupOptions: {
        input: {
          index: resolve(__dirname, "index.html")
        },
        output: {
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
          manualChunks: id => {
            if (id.includes("node_modules")) {
              return "vendor";
            }
            return undefined;
          }
        }
      }
    },
    server: {
      open: true,
      port: 65515,
      host: "0.0.0.0",
      proxy: {
        "/maps/api": {
          target: "https://maps.googleapis.com",
          changeOrigin: true,
          rewrite: path => path?.replace?.(/^\/maps\/api/, "/maps/api")
        },
        // "/api": {
        //   target: config.VITE_TARGET,
        //   changeOrigin: true,
        //   secure: false,
        //   rewrite: path => path.replace(/^\/api/, "")
        // },
        "/api": {
          target: "http://test.sportsseier.com",
          changeOrigin: true,
          secure: false,
          rewrite: path => path.replace(/^\/api/, "")
        }
      }
    },
    resolve: {
      extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"],
      alias: {
        "@": path.resolve(__dirname, "src"),
        comps: path.resolve(__dirname, "src/components")
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use '@/styles/variables.scss' as *;`
        }
      },
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue({ file }: any) {
              return file.indexOf("vant") !== -1 ? 37.5 : appWidth / divide;
            },
            propList: ["*"],
            unitPrecision: unitPrecision,
            // selectorBlackList: ["van"], // 不被转换rem的样式
            exclude: (filePath: string) => {
              if (/src\/styles\/initial.scss/.test(filePath)) {
                return true;
              }
              return false;
            }
          })
        ]
      }
    }
  };
});
